package net.borlis.sample.web.soap.executors.common;

import net.borlis.dictionaries.product.HierarchyLevelDictionary;
import net.borlis.dictionaries.product.LifecycleStateDictionary;
import net.borlis.dictionaries.product.SaleType;
import net.borlis.sample.web.context.WeldWebContext;
import net.borlis.gen.ws.soap.ErrorCodeEnum;
import net.borlis.gen.ws.soap.HierarchyLevelsEnum;
import net.borlis.gen.ws.soap.LifecycleStateEnum;
import net.borlis.gen.ws.soap.SaleTypesEnum;

import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
import java.util.*;

/**
 * @author alex@borlis.net
 */
public final class SoapUtils {

    private SoapUtils() {
    }

    public static LifecycleStateDictionary getLifecycle(LifecycleStateEnum lc) {
        return LifecycleStateDictionary.valueOf(lc.name());
    }

    public static XMLGregorianCalendar translate(WeldWebContext context, String locale, Date date) /* throws TranslatedException */ {
        try {
            GregorianCalendar calendar = new GregorianCalendar();
            calendar.setTime(date);
            return DatatypeFactory.newInstance().newXMLGregorianCalendar(calendar);
        } catch (DatatypeConfigurationException e) {
            throw context.generateException(locale, "500", e); //todo:: add the date validation error sprint#15
        }
    }

    public static ErrorCodeEnum translate(String key) {
        final String separator = "_";
        String[] words = key.split(separator);
        StringBuilder sb = new StringBuilder();
        for (String word : words) {
            String upWord = word.substring(0,1).toUpperCase() + word.substring(1, word.length());
            sb.append(upWord);
        }
        return ErrorCodeEnum.fromValue(sb.toString());
    }

    public static Date translate(XMLGregorianCalendar calendar) {
        if(calendar == null) {
            return null;
        }
        return calendar.toGregorianCalendar().getTime();
    }

    public static Set<HierarchyLevelDictionary> translate(Collection<HierarchyLevelsEnum> wsdlEnums) {
        Set<HierarchyLevelDictionary> res = new HashSet<>();
        for (HierarchyLevelsEnum wsdlEnum : wsdlEnums) {
            res.add(HierarchyLevelDictionary.findByName(wsdlEnum.value()));
        }
        return res;
    }

    public static SaleTypesEnum translate(SaleType saleType) {
        return SaleTypesEnum.fromValue(saleType.name());
    }

    public static SaleType translate(SaleTypesEnum saleType) {
        return SaleType.valueOf(saleType.value());
    }

}
